package com.sfac.hqyj.springBoot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter(filterName = "ParamFilter")
public class ParamFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("==== Init ParamFilter ====");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("==== Do ParamFilter ====");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//        Map<String, String[]> map = httpServletRequest.getParameterMap();
//        map.put("aaa", new String[]{"bbb"});

        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpServletRequest) {
            @Override
            public String getParameter(String name) {
                String value = httpServletRequest.getParameter(name);
                if (StringUtils.isNotBlank(value)) {
                    return value.replaceAll("fuck", "***");
                }
                return super.getParameter(name);
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = httpServletRequest.getParameterValues(name);
                if (values != null && values.length > 0) {
//                    List<String> temp = new ArrayList<>();
//                    for (String value : values) {
//                        temp.add(value.replaceAll("fuck", "***"));
//                    }
//                    return temp.toArray(new String[temp.size()]);
                    return Arrays.asList(values).stream()
                            .map(item -> item.replaceAll("fuck", "***"))
                            .toArray(String[] :: new);
                }

                return super.getParameterValues(name);
            }
        };

        chain.doFilter(wrapper, httpServletResponse);
    }

    @Override
    public void destroy() {
        LOGGER.debug("==== Destroy ParamFilter ====");
    }
}
